#pragma once

#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>
#include "Mutex.hpp"
#include "Cond.hpp"


const static uint32_t gcap = 5;

template <typename T>
class BlockQueue
{
private:
    bool IsFull()
    {
        return _bq.size() >= _cap;
    }
    bool IsEmpty()
    {
        return _bq.size() == 0;
    }

public:
    BlockQueue(uint32_t cap = gcap) : _cap(cap), _c_wait_num(0), _p_wait_num(0)
    {
    }
    void Enqueue(const T &in)
    {
        {
            LockGuard lockGuard(&_lock); // 析构会自动解锁
            // 临界区代码
            while (IsFull())
            {
                _p_wait_num++;
                _p_cond.Wait(_lock);
                _p_wait_num--;
            }
            // 不满
            _bq.push(in); // 完成生产

            if (_c_wait_num > 0)
                _c_cond.NotifyOne();
        }
    }
    void Pop(T *out)
    {
        {
            LockGuard lockGuard(&_lock);
            while (IsEmpty())
            {
                _c_wait_num++;
                _c_cond.Wait(_lock);
                _c_wait_num--;
            }
            *out = _bq.front();
            _bq.pop();

            if (_p_wait_num > 0)
                _p_cond.NotifyOne();
        }
    }
    ~BlockQueue()
    {
    }

private:
    // 临界资源
    std::queue<T> _bq;
    uint32_t _cap; // 容量

    Cond _c_cond; // 消费者用的cond
    Cond _p_cond; // 生产者用的cond

    Mutex _lock;

    // 有多少线程在等待
    int _c_wait_num;
    int _p_wait_num;
};